<script setup lang='ts'>
import { useHistoryDelete, useHistoryExport, useHistoryIndex } from '@fl/api/add-elevator-api'
import type { historyIndexParam } from '@fl/api/add-elevator-api/model/history-model'
import { useGetCascadeData } from '@fl/api/elevator-api/verify'
import { SearchForm, SearchTable } from '@fl/components'
import { formatTime } from '@fl/utils'
import { hasPermi } from '@fl/utils/has-permi'
import dayjs from 'dayjs'
import { cloneDeep } from 'lodash-es'
import type { OptionsType, PlusColumn } from 'plus-pro-components'
import { reactive } from 'vue'
import type { VxeGridProps, VxePagerEvents } from 'vxe-table'
import addOrEdit from './components/add-or-edit.vue'

defineOptions({
    // eslint-disable-next-line vue/component-definition-name-casing
    name: 'retrofit-elevator-business-history',
})
const projectName = ref('')

const createVisible = ref<boolean>(false)
const editId = ref<string>('')
const currentInfo = ref<any>() // 详情接口不用了，从列表取
const records = ref<any>([])
const isReadonly = ref<boolean>(false)
const typeOptions = [
    { value: 'user_info', label: '电梯使用登记' },
    { value: 'completion_info', label: '竣工验收登记' },
    { value: 'archive_info', label: '档案归档' },
    { value: 'subsidy_application_info', label: '补贴申领' },
    { value: 'subsidy_received_info', label: '补贴到账' },
]
const flagOptions = [
    { value: '1', label: '是' },
    { value: '0', label: '否' },
]

// 搜索条件、分页参数
const initialState = {
    createTime: ['', ''],
    areaCode: '',
    streetCode: '',
    communityCode: '',
    projectId: '',
    building: '',
    unit: '',
    infoType: '',
    flag: '',
}
// const initialState = {} as any
const state = ref<historyIndexParam>(cloneDeep(initialState))
const searchConditions = ref<historyIndexParam>(cloneDeep(initialState))

const tablePage = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
})

const getAreaOptionsParams = computed(() => ({
    targetLabel: 'area',
}))
const getStreetOptionsParams = computed(() => ({
    areaCode: state.value.areaCode,
    targetLabel: 'street',
}))
const getCommunityOptionsParams = computed(() => ({
    streetCode: state.value.streetCode,
    targetLabel: 'community',
}))
const getProjectOptionsParams = computed(() => ({
    communityCode: state.value.communityCode,
    areaCode: state.value.areaCode,
    streetCode: state.value.streetCode,
    targetLabel: 'project',
    projectName: projectName.value,
}))
const getBuildingOptionsParams = computed(() => ({
    projectId: state.value.projectId,
    targetLabel: 'building',
}))
const getUnitOptionsParams = computed(() => ({
    buildingId:buildingOptions.value && state.value.building
  ? (buildingOptions.value.find(item => item.label === state.value.building)?.buildingId ?? '')
  : '',
    building: state.value.building,
    targetLabel: 'unit',
}))
const { data: areaOptions } = useGetCascadeData(getAreaOptionsParams)
const { data: streetOptions } = useGetCascadeData(getStreetOptionsParams, 'areaCode')
const { data: communityOptions } = useGetCascadeData(getCommunityOptionsParams, 'streetCode')
const { data: projectOptions, isLoading: projectLoading } = useGetCascadeData(
    getProjectOptionsParams,
    'projectName',
)
const { data: buildingOptions } = useGetCascadeData(getBuildingOptionsParams, 'projectId')
const { data: unitOptions } = useGetCascadeData(getUnitOptionsParams, 'building')
function projectSearch(keyword) {
    projectName.value = keyword
}
watch(() => state.value.areaCode, () => {
    const { building, communityCode, projectId, streetCode, unit, ...data } = state.value
    state.value = cloneDeep(data)
})

watch(() => state.value.streetCode, () => {
    const { building, communityCode, projectId, unit, ...data } = state.value
    state.value = cloneDeep(data)
})

watch(() => state.value.communityCode, () => {
    const { building, projectId, unit, ...data } = state.value
    state.value = cloneDeep(data)
})

watch(() => state.value.projectId, () => {
    const { building, unit, ...data } = state.value
    state.value = cloneDeep(data)
})

watch(() => state.value.building, () => {
    const { unit, ...data } = state.value
    state.value = cloneDeep(data)
})

// 查询列表
const params = computed(() => ({
    areaCode: searchConditions.value.areaCode,
    streetCode: searchConditions.value.streetCode,
    communityCode: searchConditions.value.communityCode,
    projectId: searchConditions.value.projectId,
    building: searchConditions.value.building,
    unit: searchConditions.value.unit,
    pageIndex: tablePage.currentPage,
    pageSize: tablePage.pageSize,
    startTime: searchConditions.value.createTime?.[0] ? formatTime(searchConditions.value.createTime[0], 'yyyy-MM-dd 00:00:00') : null,
    endTime: searchConditions.value.createTime?.[1] ? formatTime(searchConditions.value.createTime[1], 'yyyy-MM-dd 23:59:59') : null,
    infoType: searchConditions.value.infoType,
    flag: searchConditions.value.flag,
    applyNo: searchConditions.value.applyNo,
}))
const { data, isLoading } = useHistoryIndex(params)

watchEffect(() => {
    if (data.value) {
        records.value = cloneDeep(data.value.records)
        tablePage.total = data.value.total!
    }
})

// 导出
const exportParams = computed(() => ({
    areaCode: searchConditions.value.areaCode,
    streetCode: searchConditions.value.streetCode,
    communityCode: searchConditions.value.communityCode,
    projectId: searchConditions.value.projectId,
    building: searchConditions.value.building,
    unit: searchConditions.value.unit,
    startTime: searchConditions.value.createTime?.[0] ? formatTime(searchConditions.value.createTime[0], 'yyyy-MM-dd 00:00:00') : '',
    endTime: searchConditions.value.createTime?.[1] ? formatTime(searchConditions.value.createTime[1], 'yyyy-MM-dd 23:59:59') : '',
    infoType: searchConditions.value.infoType,
    flag: searchConditions.value.flag,
}))
const { isPending, mutateAsync } = useHistoryExport(exportParams)
async function exportData() {
    const res = await mutateAsync()
    if (res) {
        const objectUrl = URL.createObjectURL(res)
        location.href = objectUrl
        URL.revokeObjectURL(objectUrl)
    }
}

function submit() {
    searchConditions.value = cloneDeep(state.value)
    resetTablePage()
}

function reset() {
    state.value = cloneDeep(initialState)
    searchConditions.value = cloneDeep(initialState)
    resetTablePage()
}

function resetTablePage() {
    tablePage.currentPage = 1
    tablePage.pageSize = 10
}

// 新增
function goToAdd() {
    createVisible.value = true
    editId.value = ''
    currentInfo.value = {}
    isReadonly.value = false
}

// 列表：编辑
function goToEdit(row: any) {
    createVisible.value = true
    editId.value = String(row.id)
    currentInfo.value = cloneDeep(row)
    isReadonly.value = false
}

// 列表：删除
const { mutate: deleteMutate } = useHistoryDelete()
function goToDel(row: any) {
    deleteMutate(row.id, {
        onSuccess: () => {
            ElMessage.success('操作成功')
        },
    })
}

// 列表：详情
function goToShow(row: any) {
    createVisible.value = true
    editId.value = String(row.id)
    currentInfo.value = cloneDeep(row)
    isReadonly.value = true
}

const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.currentPage = currentPage
    tablePage.pageSize = pageSize
}

const columns: PlusColumn[] = [
    {
        colProps: {
            span: 6,
        },
        fieldProps: {
            filterable: true,
        },
        label: '所在区',
        options: areaOptions as OptionsType,
        prop: 'areaCode',
        valueType: 'select',
    },
    {
        colProps: {
            span: 6,
        },
        fieldProps: {
            filterable: true,
        },
        label: '街道',
        options: streetOptions as OptionsType,
        prop: 'streetCode',
        valueType: 'select',
    },
    {
        colProps: {
            span: 6,
        },
        fieldProps: {
            filterable: true,
        },
        label: '社区',
        options: communityOptions as OptionsType,
        prop: 'communityCode',
        valueType: 'select',
    },
    {
        colProps: {
            span: 6,
        },
        // fieldProps: {
        //     filterable: true,
        // },
        label: '小区',
        // options: projectOptions as OptionsType,
        prop: 'projectId',
        // valueType: 'select',
    },
    {
        colProps: {
            span: 6,
        },
        fieldProps: {
            filterable: true,
        },
        label: '栋',
        options: buildingOptions as OptionsType,
        prop: 'building',
        valueType: 'select',
    },
    {
        colProps: {
            span: 6,
        },
        fieldProps: {
            filterable: true,
        },
        label: '单元',
        options: unitOptions as OptionsType,
        prop: 'unit',
        valueType: 'select',
    },
    {
        colProps: {
            span: 12,
        },
        fieldProps: {
            'endPlaceholder': '结束时间',
            'startPlaceholder': '开始时间',
            'type': 'daterange',
            'value-format': 'YYYY-MM-DD HH:mm:ss',
            'disabled-date': (time: Date) => {
                return dayjs(time).isAfter(dayjs(new Date()).format('YYYY-MM-DD 23:59:59'))
            },
        },
        label: '发布日期',
        prop: 'createTime',
        valueType: 'date-picker',
    },
    {
        colProps: {
            span: 6,
        },
        label: '申请编号',
        prop: 'applyNo',
    },
    {
        colProps: {
            span: 8,
        },
        label: '加梯信息',
        prop: 'infoType',
    },
]
const gridOptions = reactive<VxeGridProps>({
    columns: [
        { title: '序号', type: 'seq', width: 60 },
        { field: 'applyNo', title: '申请编号' },
        { field: 'areaName', title: '区' },
        { field: 'streetName', title: '街道' },
        { field: 'communityName', title: '社区' },
        { field: 'projectName', title: '小区' },
        { field: 'building', slots: { default: 'building' }, title: '栋-单元楼' },
        { field: 'num', title: '栋数' },
        { field: 'createTime', title: '创建时间', minWidth: 100 },
        { slots: { default: 'operate' }, title: '操作', width: 160 },
    ],
})
</script>

<template>
    <ElCard class="mb-20"
            shadow="never"
    >
        <SearchForm v-model="state"
                    :columns="columns"
                    submit-text="搜索"
                    @reset="reset"
                    @submit="submit"
        >
            <template #plus-field-projectId>
                <el-select v-model="state.projectId"
                           filterable
                           remote
                           reserve-keyword
                           placeholder="直接搜小区,无需选区域"
                           remote-show-suffix
                           :remote-method="projectSearch"
                           :loading="projectLoading"
                >
                    <el-option v-for="item in projectOptions"
                               :key="item.value"
                               :label="item.label"
                               :value="item.value"
                    />
                </el-select>
            </template>

            <template #plus-field-infoType>
                <div class="flex w-[100%]">
                    <el-select v-model="state.infoType"
                               class="flex-1"
                    >
                        <el-option v-for="i in typeOptions"
                                   :key="i.value"
                                   :label="i.label"
                                   :value="i.value"
                        />
                    </el-select>

                    <el-select v-model="state.flag"
                               class="ml-10"
                               style="width:100px;"
                    >
                        <el-option v-for="i in flagOptions"
                                   :key="i.value"
                                   :label="i.label"
                                   :value="i.value"
                        />
                    </el-select>
                </div>
            </template>
        </SearchForm>
    </ElCard>

    <ElCard shadow="never">
        <SearchTable v-bind="gridOptions"
                     v-model:pager="tablePage"
                     :loading="isLoading"
                     :data="records"
                     @page-change="handlePageChange"
        >
            <template #toolbar_buttons>
                <ElButton v-if="hasPermi('历史数据-补录')"
                          type="primary"
                          @click="goToAdd"
                >
                    <div class="i-ic:baseline-add size-16" />
                    历史数据补录
                </ElButton>

                <ElButton type="primary"
                          plain
                          :loading="isPending"
                          @click="exportData"
                >
                    <div class="i-iconamoon:upload size-16" />
                    导出
                </ElButton>
            </template>

            <template #building="{ row }">
                {{ row.building }}-{{ row.unit }}
            </template>

            <template #operate="{ row }">
                <el-button v-if="hasPermi('历史数据-编辑')"
                           class="small"
                           type="primary"
                           text
                           @click="goToEdit(row)"
                >
                    编辑
                </el-button>

                <el-popconfirm title="确认删除吗？"
                               @confirm="goToDel(row)"
                >
                    <template #reference>
                        <el-button v-if="hasPermi('历史数据-删除')"
                                   class="small"
                                   text
                                   type="warning"
                        >
                            删除
                        </el-button>
                    </template>
                </el-popconfirm>

                <el-button v-if="hasPermi('历史数据-详情')"
                           text
                           @click="goToShow(row)"
                >
                    详情
                </el-button>
            </template>
        </SearchTable>
    </ElCard>

    <addOrEdit v-model:visible="createVisible"
               v-model:id="editId"
               v-model:is-readonly="isReadonly"
               v-model:info="currentInfo"
    />
</template>

<style lang="scss" scoped>
:deep(.small.el-button) {
    padding: 4px;
    margin-left: 6px;
}
</style>
